package com.cswangdao.typehandler;

import cn.hutool.json.JSONUtil;
import com.cswangdao.utils.JacksonUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Integer[].class)
public class StringToIntegerArrayTypeHandler implements TypeHandler<Integer[]> {


    @Override
    public void setParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JacksonUtil.write(parameter));
    }

    @Override
    public Integer[] getResult(ResultSet rs, String columnName) throws SQLException {
        String jsonStr = rs.getString(columnName);
        Integer[] integers = JacksonUtil.read(jsonStr, Integer[].class);
        return integers;
    }

    @Override
    public Integer[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonStr = rs.getString(columnIndex);
        Integer[] integers = JacksonUtil.read(jsonStr, Integer[].class);
        return integers;
    }

    @Override
    public Integer[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonStr = cs.getString(columnIndex);
        Integer[] integers = JacksonUtil.read(jsonStr, Integer[].class);
        return integers;
    }
}
